import React, { useState } from 'react';
import Select from 'react-select';

const options = [
  {
    label: '北京',
    value: 'Beijing',
    children: [
      { label: '东城区', value: 'Dongcheng' },
      { label: '西城区', value: 'Xicheng' },
      { label: '海淀区', value: 'Haidian' }
    ]
  },
  {
    label: '上海',
    value: 'Shanghai',
    children: [
      { label: '浦东新区', value: 'Pudong' },
      { label: '黄浦区', value: 'Huangpu' },
      { label: '静安区', value: 'Jingan' }
    ]
  },
  {
    label: '广州',
    value: 'Guangzhou',
    children: [
      { label: '天河区', value: 'Tianhe' },
      { label: '越秀区', value: 'Yuexiu' },
      { label: '海珠区', value: 'Haizhu' }
    ]
  }
];

function CascadingSelect() {
  const [selectedOption, setSelectedOption] = useState(null);

  const handleChange = selectedOption => {
    setSelectedOption(selectedOption);
  };

  return (
    <div>
      <Select options={options} value={selectedOption} onChange={handleChange} placeholder='Select a province' isClearable />

      {selectedOption && selectedOption.children && (
        <Select
          options={selectedOption.children}
          placeholder='Select a city'
          isClearable
          onChange={selectedOption =>
            handleChange({
              ...selectedOption,
              label: `${selectedOption.label} (${selectedOption.parentLabel})`
            })
          }
          getOptionLabel={option => option.label}
          getOptionValue={option => option.value}
          formatOptionLabel={option => (
            <div>
              <span>{option.label}</span>
              <span style={{ color: 'gray', marginLeft: '0.5rem' }}>({selectedOption.label})</span>
            </div>
          )}
        />
      )}

      {selectedOption && selectedOption.parentLabel && (
        <Select
          options={[
            {
              label: 'Select a district',
              value: '',
              isDisabled: true
            },
            ...selectedOption.districts.map(district => ({
              label: district,
              value: district
            }))
          ]}
          placeholder='Select a district'
          isClearable
          onChange={selectedOption => handleChange(selectedOption)}
        />
      )}
    </div>
  );
}

export default CascadingSelect;
